package control;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;

import dao.DAOFactory;
import dao.Entidad;

import bean.Proveedor;

/**
 * Servlet implementation class Servlet
 */
@WebServlet("/ServletProveedor")
public class ServletProveedor extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServletProveedor() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		if(request.getParameter("action")!=null){
			String action=(String)request.getParameter("action");
			List<Proveedor> listProveedor= new ArrayList<Proveedor>();
			Gson gson = new Gson();
			response.setContentType("application/json");
			DAOFactory factory=DAOFactory.getFactoryConcrete(DAOFactory.MYSQL);
			Entidad<Proveedor> proveedordao= factory.getProveedorDAO();
			System.out.println("ACCION: "+request.getParameter("action"));
			if(action.equals("list")){
				try{
					
					listProveedor = proveedordao.listAll();					
					
					JsonElement element = gson.toJsonTree(listProveedor,new TypeToken<List<Proveedor>>(){}.getType());
					JsonArray jsonArray = element.getAsJsonArray();
					String listData=jsonArray.toString();
					
					listData="{\"Result\":\"OK\",\"Records\":"+listData+"}";					
					
					response.setHeader("Cache-control", "no-cache, no-store");
			        response.setHeader("Pragma", "no-cache");
			        response.setHeader("Expires", "-1");
					response.getWriter().print(listData);
					System.out.println(listData);
					
				}catch(Exception ex){
					String error="{\"Result\":\"ERROR\",\"Message\":"+ex.getStackTrace()+"}";
					response.getWriter().print(error);
					System.out.println(error);
				}
				
			}else if(action.equals("create") || action.equals("update")){
			    Proveedor proveedor=new Proveedor();
			    
			    try{
			    	
			    if(request.getParameter("id_prov")!=null){       
				       int proveedorid=Integer.parseInt(request.getParameter("id_prov"));
				       proveedor.setId_prov(proveedorid);
				       System.out.println("IDDDD : " +proveedorid );
			    }
			    if(request.getParameter("razo_soci")!=null){
				       String nombre=(String)request.getParameter("razo_soci");
				       proveedor.setRazo_soci(nombre);
			    }
			    if(request.getParameter("dire")!=null){
				       String descripcion=(String)request.getParameter("dire");
				       proveedor.setDire(descripcion);
			    }
			    if(request.getParameter("tele")!=null){
				       String telefono=(String)request.getParameter("tele");
				       proveedor.setTele(telefono);
			    }
			    if(request.getParameter("ruc")!=null){
				       String ruc=(String)request.getParameter("ruc");
				       proveedor.setRuc(ruc);
				}
			    if(request.getParameter("repr")!=null){
				       String representante=(String)request.getParameter("repr");
				       proveedor.setRepr(representante);
				}
			    }catch(Exception e){
			    	System.out.print("Error al capturar datos " + e.getMessage());
			    }
			    
			    try{           
			     if(action.equals("create")){//Create new record
			      proveedordao.insert(proveedor);     
			      listProveedor.add(proveedor);
			      //Convert Java Object to Json    
			      String json=gson.toJson(proveedor);     
			      //Return Json in the format required by jTable plugin
			      String listData="{\"Result\":\"OK\",\"Record\":"+json+"}";           
			      response.getWriter().print(listData);
			     }else if(action.equals("update")){//Update existing record
			      proveedordao.update(proveedor);
			      String listData="{\"Result\":\"OK\"}";         
			      response.getWriter().print(listData);
			     }
			    }catch(Exception ex){
			      String error="{\"Result\":\"ERROR\",\"Message\":"+ex.getStackTrace().toString()+"}";
			      response.getWriter().print(error);
			    }
			   }else if(action.equals("delete")){//Delete record
			    try{
			     if(request.getParameter("id_prov")!=null){
			     Proveedor proveedor=new Proveedor();
			     	try{
			     		if(request.getParameter("id_prov")!=null){       
			     		int proveedorid=Integer.parseInt(request.getParameter("id_prov"));
			     		proveedor.setId_prov(proveedorid);
						}
					}catch(Exception e){
					    System.out.print("Error al capturar datos " + e.getMessage());
					}
			      proveedordao.delete(proveedor);
			      String listData="{\"Result\":\"OK\"}";        
			      response.getWriter().print(listData);
			     }
			    }catch(Exception ex){
			    String error="{\"Result\":\"ERROR\",\"Message\":"+ex.getStackTrace().toString()+"}";
			    response.getWriter().print(error);
			   }    
			  }

			
			
		}
		
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		doGet(request, response);
	}

}
